package com.b2c.erp.controller;

import com.alibaba.fastjson.JSONObject;
import com.b2c.common.utils.StringUtil;
import com.b2c.entity.DataRow;
import com.b2c.entity.ErpGoodsSpecMoveFromEntiy;
import com.b2c.entity.ErpStockLocationBatchAddVo;
import com.b2c.entity.ErpStockLocationEntity;
import com.b2c.entity.erp.vo.ErpGoodsSpecVo;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.interfaces.wms.StockLocationService;
import com.b2c.interfaces.wms.StockService;
import com.b2c.erp.response.ApiResult;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 描述：
 * 商品库存AJAX
 *
 * @author qlp
 * @date 2019-03-20 10:40
 */
@RequestMapping(value = "/ajax_stock")
@RestController
public class AjaxStockLocationController {
    @Autowired
    private StockLocationService stockLocationService;
    @Autowired
    private StockService stockService;
    @Autowired
    private ErpUserActionLogService logService;

    private static Logger log = LoggerFactory.getLogger(AjaxStockLocationController.class);

    /**
     * 添加仓库
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/add_stock_house", method = RequestMethod.POST)
    public ApiResult<Integer> addStockHouse(@RequestBody DataRow model, HttpServletRequest request) {
        String number = model.getString("number");
        String name = model.getString("name");
        if (stockLocationService.getIdByNumber(number) > 0) return new ApiResult<>(400, "仓库编号已存在");
        if (stockLocationService.getIdByName(name) > 0) return new ApiResult<>(400, "仓库名称已存在");
        //新增仓库
        stockLocationService.addStockHouse(number, name);
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/ajax_stock/add_stock_house","添加仓库 , 名称 : "+number+" 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");

        return new ApiResult<>(0, "新增成功");
    }

    /**
     * 修改仓库
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/update_stock_house", method = RequestMethod.POST)
    public ApiResult<Integer> updateStockHouse(@RequestBody DataRow model, HttpServletRequest request) {
        Integer id = Integer.parseInt(model.getString("id"));
        String number = model.getString("number");
        String name = model.getString("name");

        if (stockLocationService.getIdByNumber(number) > 0 && stockLocationService.getIdByNumber(number) != id)
            return new ApiResult<>(400, "仓库编号已存在");
        if (stockLocationService.getIdByName(name) > 0 && stockLocationService.getIdByName(name) != id)
            return new ApiResult<>(400, "仓库名称已存在");

        stockLocationService.updateStockHouse(id, number, name);
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/ajax_stock/update_stock_house","修改仓库 , id : "+id+" ,修改前名称 : "+number+" 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");

        return new ApiResult<>(0, "修改成功");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/del_stock_house", method = RequestMethod.POST)
    public ApiResult<Integer> delStockCategory(@RequestBody Integer id , HttpServletRequest request) {
        ResultVo<Integer> resultVo = stockLocationService.delStockHouse(id);
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/ajax_stock/del_stock_house","删除仓库 , id : "+id+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),resultVo.getMsg());

        if (resultVo.getCode() > 0) return new ApiResult<>(404, resultVo.getMsg());
        return new ApiResult<>(0, "删除成功");
    }

    /**
     * 添加库区
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "add_reservoir", method = RequestMethod.POST)
    public ApiResult<Integer> addStockReservoir(@RequestBody DataRow model, HttpServletRequest request) {
        String number = model.getString("number");
        String name = model.getString("name");
        int store_house = model.getInt("store_house");
        if (stockLocationService.getIdByNumber(number) > 0) return new ApiResult<>(400, "库区编号已存在");
        if (stockLocationService.getIdByName(name) > 0) return new ApiResult<>(400, "库区名称已存在");
        //新增仓库
        int result = stockLocationService.addReservoir(number, name, store_house);
        if (result == -404){
            //添加系统日志
            logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                    "/ajax_stock/add_reservoir","添加库区 , 名称 : "+number+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"仓库不存在");
            return new ApiResult<>(404, "仓库不存在");
        }
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/ajax_stock/add_reservoir","添加库区 , 名称 : "+number+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"新增成功");
        return new ApiResult<>(0, "新增成功");
    }

    /**
     * 修改库区
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/update_reservoir", method = RequestMethod.POST)
    public ApiResult<Integer> updateReservoir(@RequestBody DataRow model, HttpServletRequest request) {
        Integer id = Integer.parseInt(model.getString("id"));
        String number = model.getString("number");
        String name = model.getString("name");
        int store_house = model.getInt("store_house");
        //if ( reservoirService.getIdByNumber(number) == id) return new ApiResult<>(400,"库区编号已存在");
        //if ( reservoirService.getIdByName(name) == id) return new ApiResult<>(400,"库区名称已存在");

        stockLocationService.updateReservoir(id, number, name, store_house);
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/ajax_stock/update_reservoir","修改库区 , id : "+id+" ,修改前名称 : "+number+" 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");

        return new ApiResult<>(0, "修改成功");
    }

    /**
     * 根据仓库ID获取库区信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/get_reservoir", method = RequestMethod.POST)
    public ApiResult<List> getReservoir(@RequestBody Object id) {
        List<ErpStockLocationEntity> list = stockLocationService.getListByParentId((int) id);
        return new ApiResult<>(0, "SUCCESS", list);
    }

    /**
     * 添加库区
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "add_shelf", method = RequestMethod.POST)
    public ApiResult<Integer> addShelf(@RequestBody DataRow model, HttpServletRequest request) {
        String number = model.getString("number");
        String name = model.getString("name");
        Integer houseId = model.getInt("houseId");
        Integer reservoir = model.getInt("reservoirId");

        if (StringUtils.isEmpty(number) || StringUtils.isEmpty(name))
            return new ApiResult<>(401, "仓位编号和仓位名不能为空");
        if (houseId == 0 || reservoir == 0)
            return new ApiResult<>(402, "请选择仓库和库区");

        if (stockLocationService.getIdByNumber(number) > 0) return new ApiResult<>(400, "仓位编号已存在");
//        if (stockLocationService.getIdByName(name) > 0) return new ApiResult<>(400, "仓位名称已存在");

        //新增仓库
        int result = stockLocationService.addShelf(number, name, houseId, reservoir);
        if (result == -404) return new ApiResult<>(400, "仓库已存在");
        else if (result == -403) return new ApiResult<>(400, "仓位已存在");
        else if (result == -405) return new ApiResult<>(400, "库区已存在");
        else if (result == 0) return new ApiResult<>(500, "系统异常");
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/goods_loss_stock/add_shelf","添加仓位 , 名称 : "+number+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");

        return new ApiResult<>(0, "新增成功");
    }

    /**
     * 修改库区
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/update_shelf", method = RequestMethod.POST)
    public ApiResult<Integer> updateShelf(@RequestBody DataRow model, HttpServletRequest request) {
        Integer id = Integer.parseInt(model.getString("id"));
        String number = model.getString("number");
        String name = model.getString("name");
        Integer store_house = model.getInt("store_house");
        Integer reservoir = model.getInt("reservoir");
        //if ( shelfService.getIdByNumber(number) == id) return new ApiResult<>(400,"库区编号已存在");
        //if ( shelfService.getIdByName(name) == id) return new ApiResult<>(400,"库区名称已存在");

        stockLocationService.updateShelf(id, number, name, store_house, reservoir);
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/goods_loss_stock/update_shelf","修改仓位 , id : "+id+" ,修改前名称 : "+number+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");

        return new ApiResult<>(0, "修改成功");
    }

    /**
     * 批量导入仓位信息(excel)
     *
     * @param file
     * @param req
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @RequestMapping(value = "/shelf_excel_import", method = RequestMethod.POST)
    public ApiResult<Integer> shelfImportExcel(@RequestParam("excel") MultipartFile file, HttpServletRequest request) throws IOException, InvalidFormatException {
        int totalSuccess = 0;
        int isExist = 0;//已存在数量
        int totalError = 0;
        String fileName = file.getOriginalFilename();
        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
        System.out.println(destFileName);
        File destFile = new File(destFileName);
        file.transferTo(destFile);

        System.out.println("上传成功");
        System.out.println("开始读取EXCEL内容");

        Workbook workbook = null;
        InputStream fis = null;
        //读取到的数据
        var shelfList = new ArrayList<ErpStockLocationBatchAddVo>();

        try {
            fis = new FileInputStream(destFileName);

            if (fileName.toLowerCase().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (fileName.toLowerCase().endsWith("xls")) {
                workbook = new HSSFWorkbook(fis);
            }

            Sheet sheet = workbook.getSheetAt(0);

            //得到行的迭代器
            Iterator<Row> rowIterator = sheet.iterator();
            int rowCount = 0;
            //循环每一行
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                //从第二行开始
                if (rowCount > 0) {
                    if (StringUtils.isEmpty(row.getCell(2).getStringCellValue()) == false) {
                        var excelEntity = new ErpStockLocationBatchAddVo();
                        try {
                            //仓库编码
                            excelEntity.setHouseNo(StringUtil.getCellValue(row.getCell(0)));
                            //库区编码
                            excelEntity.setReservoirNo(row.getCell(1).getStringCellValue());
                            //仓位编码
                            excelEntity.setNumber(row.getCell(2).getStringCellValue());
                            //仓位名
                            excelEntity.setName(excelEntity.getNumber());

                        } catch (Exception e) {
//                        throw e;
                            return new ApiResult<>(505, "第" + rowCount + "行" + "数据格式错误");
                        }
                        shelfList.add(excelEntity);
                    }
                }
                rowCount++;
            }
        } catch (Exception ex) {
            return new ApiResult<>(500, ex.getMessage());
        }

        if (shelfList == null || shelfList.size() == 0) return new ApiResult<>(404, "没有数据");

        for (var i : shelfList) {
            //添加到数据库
            var result = stockLocationService.batchAddShelf(i);

            if (result.getCode() == EnumResultVo.SUCCESS.getIndex()){
                totalSuccess++;
                log.info("添加成功"+ JSONObject.toJSONString(i));
            }
            else if (result.getCode() == EnumResultVo.DataExist.getIndex()) {
                log.info("添加失败，已经存在"+ JSONObject.toJSONString(i));
                isExist++;
            }
            else if(result.getCode() == EnumResultVo.DataError.getIndex()){
                return new ApiResult<>(result.getCode(),result.getMsg());
            }
            else totalError++;
        }
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Query,
                "/ajax_stock/shelf_excel_import","批量导入仓位信息 , 添加成功：" + totalSuccess + "，重复数据：" + isExist + " ，数据错误：" + totalError+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");

        return new ApiResult<>(0, "添加成功：" + totalSuccess + "，重复数据：" + isExist + " ，数据错误：" + totalError);
    }


    @RequestMapping(value = "/goods_spec_by_number", method = RequestMethod.POST)
    public ApiResult<List<ErpGoodsSpecVo>> getErpGoodsSpec(@RequestBody DataRow data) {
        if (StringUtils.isEmpty(data.getString("locationId")))
            return new ApiResult<>(EnumResultVo.DataError.getIndex(), "请选择出库仓库");
        if (StringUtils.isEmpty(data.getString("rreservoirId")))
            return new ApiResult<>(EnumResultVo.DataError.getIndex(), "请选择出库货区");
        if (StringUtils.isEmpty(data.getString("shelfId")))
            return new ApiResult<>(EnumResultVo.DataError.getIndex(), "请选择出库货架");

        List<ErpGoodsSpecVo> list = stockService.getGoodSpecByMoveSpec(data.getInt("locationId"), data.getInt("rreservoirId"), data.getInt("shelfId"), data.getString("number"));
        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "", list);
    }

    @RequestMapping(value = "/get_move_house_list", method = RequestMethod.POST)
    public ApiResult<ErpGoodsSpecMoveFromEntiy> getIdByEntiy(@RequestBody DataRow data) {
        ErpGoodsSpecMoveFromEntiy entiy = stockService.getIdByErpGoodsSpecMoveFromEntiy(Integer.parseInt(data.getString("id")));
        entiy.setOld_locationName(stockLocationService.getName(entiy.getOldLocationId()));

        entiy.setOld_reservoirName(stockLocationService.getName(entiy.getOldReservoirId()));

        entiy.setOld_shelfName(stockLocationService.getName(entiy.getOldShelfId()));

        entiy.setNewlocationName(stockLocationService.getName(entiy.getNewLocationId()));

        entiy.setNewReservoirName(stockLocationService.getName(entiy.getNewReservoirId()));

        entiy.setNewShelfName(stockLocationService.getName(entiy.getNewShelfId()));

        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long createTime = entiy.getCreateTime().longValue();
        String time = sd.format(createTime * 1000);
        entiy.setDataTime(time);
        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "", entiy);
    }

    /**
     * 根据仓库编码查询仓位
     * @param data
     * @return
     */
    @RequestMapping(value = "/get_stock_location_by_number", method = RequestMethod.POST)
    public ApiResult<List<ErpStockLocationEntity>> getStockLocationByNumber(@RequestBody DataRow data) {
        if (StringUtils.isEmpty(data.getString("number")))
            return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "", null);

        var list = stockLocationService.getListByNumber(data.getString("number"));
        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "", list);
    }


}
